<script setup>
import { onMounted, ref } from 'vue';
import { getAdPage, queryAd, deleAd, editAd, addAd, getPhoneName, offAdApi, onAdApi } from '@/apis/ad.js';
import {Plus,Search} from "@element-plus/icons-vue";
import { uploadImg } from "@/apis/common.js";
import { formatTime } from "@/utils/time_common.js";



const total = ref(0);
const current = ref(1);
const size = ref(10);
const phoneCategoryName = ref([])
const queryName = ref('');
const tableData = ref([]);
const drawer = ref(false)
const uploadRef = ref()
const classData = ref({
  adId: '',
  title: '',
  categoryId: '',
  imgUrl: '',
  remarks: ''
});
const fileList = ref([])
const VITE_IMG_UPLOAD_PATH = import.meta.env.VITE_IMG_UPLOAD_PATH
const VITE_BASE_URL = import.meta.env.VITE_BASE_URL
let Authorization = { Authorization: localStorage.getItem("accessToken") }

//初始化函数
const init = async () => {
  await getPhoneName().then((res) => {
    if (res.data.code == 1) {
      console.log(res)
      phoneCategoryName.value = res.data.data
    }
  }
  );
  await getAdPage({ current: current.value, size: size.value }).then((res) => {
    if (res.data.code === 1) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      // Handle error
      console.log(res.data.msg)
    }
  }).catch((err) => {
    // Handle error
    console.log(err);
  });
};

const handleQuery = () => {
  current.value = 1;
  init();
};


//查询
const findHandle = () => {
  const params = {
    title: queryName.value,
    current: current.value,
    size: size.value,
  };
  queryAd(params).then((res) => {
    if (res.data.code === 1) {
      // Handle success
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      // Handle error
      ElMessage(res.data.msg)
    }
  }).catch((err) => {
    // Handle error
  });
};
//格式化分类
function formatCategory(row) {
  const category = phoneCategoryName.value.find((category) => category.id === row.categoryId);
  return category ? category.name : '未设置分类'; // 如果找不到匹配的分类，返回一个默认提示
}
//格式化状态
function formatStatus(row) {
  return row.status ? '上架' : '下架';
}
//格式化更新时间
function formatUpdateTime(row) {
  return formatTime(row.updateTime);
}
//格式化创建时间
function formatCreateTime(row) {
  return formatTime(row.createTime);
}

// 新增广告。打开弹窗
const addHandle = () => {
  classData.value.title = '';
  classData.value.action = 'add';
  classData.value.categoryId = '';
  classData.value.imgUrl = '';
  classData.value.remarks = '';
  drawer.value = true;
};

//编辑广告，打开弹窗
const editHandle = (dat) => {
  classData.value.action = 'edit';
  classData.value.title=dat.title
  classData.value.categoryId = dat.categoryId;
  classData.value.imgUrl = dat.imgUrl;
  classData.value.adId = dat.adId;
  classData.value.remarks = dat.remarks;
  drawer.value = true;
};

//关闭弹窗
const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    done();
  }).catch(() => {
  });
};

//下架
const offAd = (id) => {
  const confirmText = '此操作将下架该广告, 是否继续?';
  const confirmTitle = '提示';
  const confirmType = 'warning';

  ElMessageBox.confirm(confirmText, confirmTitle, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: confirmType,
  }).then(() => {
    offAdApi(id).then((res) => {
      if (res.data.code === 1) {
        // Handle success
        handleQuery();
      } else {
        // Handle error
      }
    }).catch((err) => {
      // Handle error
    });
  });
};

//上架
const onAd = (id) => {
  const confirmText = '此操作将上架除该分类, 是否继续?';
  const confirmTitle = '提示';
  const confirmType = 'warning';

  ElMessageBox.confirm(confirmText, confirmTitle, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: confirmType,
  }).then(() => {
    onAdApi(id).then((res) => {
      if (res.data.code === 1) {
        // Handle success
        handleQuery();
      } else {
        // Handle error
      }
    }).catch((err) => {
      // Handle error
    });
  });
};

//删除
const deleteHandle = (id) => {
  const confirmText = '此操作将永久删除该广告, 是否继续?';
  const confirmTitle = '提示';
  const confirmType = 'warning';

  ElMessageBox.confirm(confirmText, confirmTitle, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: confirmType,
  }).then(() => {
    deleAd(id).then((res) => {
      if (res.data.code === 1) {
        // Handle success
        handleQuery();
      } else {
        // Handle error
      }
    }).catch((err) => {
      // Handle error
    });
  });
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M!')
    return false
  }
  return true
}

// 上传图片，把图片先缓存在浏览器本地，然后再上传
const handleChange = (file) => {
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = (e) => {
    classData.value.imgUrl = e.target.result;
  };
}

// 上传图片
const uploadIcon = async () => {
  await uploadImg(classData.value.imgUrl).then((res) => {
    if (res.code === 1) {
      classData.value.imgUrl = res.data.url;
      console.log(classData.value.imgUrl)
    } else {
      this.$message.error(res.msg || '操作失败');
    }
  }).catch((err) => {
    this.$message.error('请求出错了：' + err);
  }
  );
}

// 图片上传成功回调
const uploadSuccess = (res) => {
  // 得到返回的图片地址
  classData.value.imgUrl = res.data;
  console.log('图片成功回调')
  submitAd()
}


const submitForm = async () => {
  const valid = (classData.value.categoryId === null || classData.value.categoryId) && (classData.value.imgUrl === null || classData.value.imgUrl);
  if (valid) {
    if (classData.value.imgUrl.startsWith("data:image/")) {
      uploadRef.value.submit()
    } else
      submitAd()
  } else {
    ElMessage.error('请填写完整信息！');
  }
};
// 执行添加或者编辑
const submitAd = () => {
  if (classData.value.action === 'add') {
    console.log('正在添加')
    addAd(classData.value).then((res) => {
      if (res.data.code === 1) {
        // Handle success
        handleQuery();
        drawer.value = false;
        ElMessage.success('添加成功')

      } else {
        // Handle error
        ElMessage(res.data.msg)
      }
    }).catch((err) => {
      // Handle error
    });
  } else {
    editAd(classData.value).then((res) => {
      if (res.data.code === 1) {
        // Handle success
        handleQuery();
        drawer.value = false;
        ElMessage.success('修改成功')
      } else {
        // Handle error
        ElMessage(res.data.msg)
      }
    }).catch((err) => {
      // Handle error
    });
  }
  classData.value = {
    title: '',
    adId: '',
    categoryId: '',
    imgUrl: '',
    action: '',
    remarks: ''
  }
};

const currentChange = (val) => {
  current.value = val;
  init();
};

onMounted(() => {
  init();
});
</script>

<template>
  <div id="category-app" class="dashboard-container">
    <div class="container">
      <div class="tableBar">
        <el-form :inline="true">
          <el-form-item label="广告标题" prop="name">
            <el-input v-model="queryName" clearable placeholder="请输入广告标题"></el-input>
          </el-form-item>
          <el-form-item label-width="0" prop="find">
            <el-button :icon="Search" type="primary" @click="findHandle">查询</el-button>
          </el-form-item>
          <el-form-item label-width="0" prop="add">
            <el-button :icon="Plus" type="primary" @click="addHandle">添加</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" class="tableBox" stripe>
        <el-table-column label="广告ID" prop="adId"></el-table-column>
        <el-table-column label="广告标题" prop="title"></el-table-column>
        <el-table-column :formatter="formatCategory" label="对应分类" prop="categoryId"></el-table-column>
        <el-table-column :formatter="formatCreateTime" label="创建时间" prop="createTime">
          <!--          <template v-slot="{ row }">{{ row.updateTime }}</template>-->
        </el-table-column>
        <el-table-column :formatter="formatUpdateTime" label="更新时间" prop="updateTime"> </el-table-column>
        <el-table-column :formatter="formatStatus" label="广告状态" prop="status"> </el-table-column>
        <el-table-column label="广告图片" prop="img">
          <template v-slot="{ row }">
            <img :src="`${row.imgUrl}`" alt="" height="50" width="50">
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks">
        </el-table-column>
        <el-table-column align="center" label="操作" width="190">
          <template v-slot="{ row }">
            <el-button class="blueBug" size="small" type="text" @click="editHandle(row)">修改</el-button>
            <el-button v-if="row.status" class="delBut" size="small" type="text" @click="offAd(row.adId)">下架</el-button>
            <el-button v-else class="blueBug" size="small" type="text" @click="onAd(row.adId)">上架</el-button>
            <el-button class="delBut" size="small" type="text" @click="deleteHandle(row.adId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="current" :total=total background class="pageList" layout="prev, pager, next"
        @current-change="currentChange" />
    </div>
    <el-drawer v-model=drawer :before-close="handleClose" title="广告详情" size="30%">
      <el-form class="demo-form-inline" label-width="100px">
        <el-form-item label="广告标题">
          <el-input v-model="classData.title" maxlength="14" placeholder="请输入广告标题" />
        </el-form-item>
        <el-form-item label="对应分类">
          <el-select v-model="classData.categoryId" placeholder="请选择分类">
            <el-option v-for="category in phoneCategoryName" :key="category.id" :label="category.name" :value="category.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item height="100px" label="广告图片：" width="120px">
          <el-upload ref="uploadRef" :auto-upload=false :before-upload="beforeAvatarUpload" :file-list="fileList"
            :multiple="false" :headers="Authorization" :on-change="handleChange" :on-success="uploadSuccess"
            :show-file-list="false" accept=".png, .jpg, .jpeg" :action=VITE_IMG_UPLOAD_PATH class="avatar-uploader"
            list-type="picture-card">
            <img v-if="classData.imgUrl" :src="classData.imgUrl" alt="" class="avatar" />
            <el-icon v-else color=red>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="classData.remarks" maxlength="14" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item slot="footer" class="drawer-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submitForm()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<style scoped>
@import "@/styles/common.css";
@import "@/styles/page.css";

#category-app {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

.tableBox {
  width: 100%;
}

.tableBar {
  padding: 10px 0;
  text-align: center;
}

.pageList {
  margin: 20px 0;
  text-align: center;
}

.drawer-footer {
  display: flex;
  justify-content: space-between;
}

.continue {
  margin-left: 10px;
}

.blueBug {
  color: #409EFF;
}

.delBut {
  color: #FF4949;
}


.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>